package com.cnunicom.modules.tra.controller;

import java.util.Arrays;
import java.util.Map;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.cnunicom.common.utils.DateUtils;
import com.cnunicom.common.utils.MpUtils;
import com.cnunicom.modules.mp.service.WxMpUserService;
import com.cnunicom.modules.tra.service.UnitService;
import com.cnunicom.modules.tra.service.UnitStaffService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cnunicom.modules.tra.entity.MemberEntity;
import com.cnunicom.modules.tra.service.MemberService;
import com.cnunicom.common.utils.PageUtils;
import com.cnunicom.common.utils.R;

import javax.annotation.Resource;
import javax.validation.Valid;


/**
 * 单位会员表，与单位表相关联
 *
 * @author dzygod
 * @email dingziyuan0@gmail.com
 * @date 2019-11-27 16:44:19
 */
@RestController
@RequestMapping("tra/member")
public class MemberController {
    @Resource
    private MemberService memberService;
    @Resource
    private HashOperations<String, String, Object> hashOperations;
    @Resource
    private DefaultAcsClient defaultAcsClient;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("tra:member:list")
    public R list(@RequestParam Map<String, Object> params) {
//        PageUtils page = memberService.queryPage(params);
        PageUtils page = memberService.queryMebUnitStaffPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("tra:member:info")
    public R info(@PathVariable("id") Integer id) {
        MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("tra:member:save")
    public R save(@RequestBody @Valid MemberEntity unitMeb) {
        memberService.save(unitMeb);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("tra:member:update")
    public R update(@RequestBody MemberEntity unitMeb) {
        memberService.updateById(unitMeb);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("tra:member:delete")
    public R delete(@RequestBody Integer[] ids) {
        // 删除的时候单位表的会员总数需要减一,已使用mysql触发器解决
        memberService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 手机端用户注册
     *
     * @param member
     * @return
     */
    @RequestMapping("/register")
    public R register(@RequestBody @Valid MemberEntity member) {

        Integer mobileNum = memberService.query().eq("mobile_num", member.getMobileNum()).count();
        Integer unionId = memberService.query().eq("union_id", member.getUnionId()).count();

        if (unionId > 0) {
            return R.error("该微信号已经是会员");
        }

        if (mobileNum > 0) {
            return R.error("该手机号已经注册");
        }

        /*if (!MpUtils.isIDNumber(member.getIdCard())) {
            return R.error("身份证号不正确");
        }*/


        member.setIsDel(0);
        member.setCreateTime(DateUtils.getDateTime());

        memberService.save(member);
        redisProcesses();

        try {
            CommonResponse response = defaultAcsClient.getCommonResponse(getRequest(member.getMobileNum()));
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return R.ok("注册成功");
    }

    private CommonRequest getRequest(String phoneNum) {

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers",phoneNum);
        request.putQueryParameter("SignName", "运城市宾馆");
        request.putQueryParameter("TemplateCode", "SMS_190780116");

        return request;
    }


    private void redisProcesses() {
        //总会员数
        Boolean totalIsAbsent = hashOperations.putIfAbsent("member","totalMembers", "1");
        if (totalIsAbsent.equals(Boolean.FALSE)) {
            hashOperations.increment("member","totalMembers",1L);
        }

    }
}
